<?php

namespace app\admin\model\user;

use app\admin\model\site\PlayProject;
use app\admin\model\User;
use think\Db;
use think\Model;


class Player extends Model
{

    

    

    // 表名
    protected $table = 'player_info';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'datetime';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    protected $dateFormat='Y-m-d H:i:s';

    // 追加属性
    protected $append = [

    ];

//    protected $field=['real_name'];

    public static $allowField=['real_name','longitude','latitude','province','city','wechat','id_number','constellation','game_age','video',
        'voice_intro','images','idcard_img','is_recommend','createtime','projects','age','birthday','gender','desc','voice_time','status','skills'];


    public function getList($params){
        $EARTH=6378.137;
        $PI=3.1415926535898;
        $lat=$params['lat'];
        $lng=$params['lng'];
        $query = $this ->field("*,ROUND(2 * $EARTH* ASIN(SQRT(POW(SIN($PI*(".$lat."-latitude)/360),2)+COS($PI*".$lat."/180)* COS(latitude * $PI/180)*POW(SIN($PI*(".$lng."-longitude)/360),2))),2) as distance")
            ->with(['user'=>function($query){
            $query->withField('id,nickname,avatar,gender');
        }]);
        if( $params['gender'] ?? false) $query->where(['user.gender'=>$params['gender']]);
        if(!empty($params['nickname']))
            $query->whereLike('user.nickname',"%{$params['nickname']}%");
            $query->page($params['page'] ?? 1);

        if($params['type']=='recommend'){
            $query->where("is_recommend",1);
        }
        if($params['type']=='nearby'){
            $query->order("distance asc");
        }

        if($params['type']=='new'){
            $query->order("player.createtime desc");
        }

        if(is_numeric($params['type'])){
            $query->where("FIND_IN_SET('{$params['type']}',projects)");
        }


        $list= $query->where('player.status',1)->select();
        foreach ($list as $item){
            $item->price=$this->getPrice(explode(',',$item->projects));
        }
        return $list;
    }



    public function getInfo($uid){
        $query = $this ->field("uid,real_name,wechat,skills,video,images,gender,birthday,desc,constellation,desc,age")
            ->with(['user'=>function($query){
                $query->withField('id,nickname,avatar,gender,birthday,bio');
            }]);
        $query->where('uid',$uid);
        return $query->find();
    }

    public function user()
    {
        return $this->belongsTo('app\admin\model\User', 'uid', 'id', [], 'INNER')->field('nickname,avatar,gender')->setEagerlyType(0);
    }

    public function getPrice($project_ids){
        return PlayProject::whereIn('id',$project_ids)->min('price');
    }

}
